<?php

class BackendController extends Module
{
	/**
	 * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
	 * using two-column layout. See 'protected/views/layouts/column2.php'.
	 */
    //public $theme = 'metronic';
	//public $layout='//layouts/backend/column2';

	/**
	 * @return array action filters
	 */
	public function filters()
	{
		return array(
			'accessControl', // perform access control for CRUD operations
			//'postOnly', // we only allow deletion via POST request
		);
	}
    public function init()
    {
        if(!Yii::app()->user->isAdmin)
        {
            $this->redirect(Yii::app()->createUrl('/user/login'));
        }
    }
	/**
	 * Specifies the access control rules.
	 * This method is used by the 'accessControl' filter.
	 * @return array access control rules
	 */
	public function accessRules()
	{
		return array(

			array('deny', // allow authenticated user to perform 'create' and 'update' actions
				'actions'=>array('*'),
				'users'=>array('*'),
			),
			array('allow', // allow admin user to perform 'admin' and 'delete' actions
				'actions'=>array('*'),
				'roles'=>array('admin'),
			),
		);
	}
    public function actionMain()
    {
       $this->render('main');
    }
	/**
	 * Displays a particular model.
	 * @param integer $id the ID of the model to be displayed
	 */
	public function actionView($id)
	{

		$this->render('view',array(
			'model'=>$this->loadModel($id),
		));
	}

	/**
	 * Creates a new model.
	 * If creation is successful, the browser will be redirected to the 'view' page.
	 */
	public function actionCreate()
	{
		$model=new User;

		// Uncomment the following line if AJAX validation is needed
		 $this->performAjaxValidation($model);

		if(isset($_POST['User']))
		{
			$model->attributes=$_POST['User'];

            $model->image=CUploadedFile::getInstance($model,'avatar');

            if(isset($model->image))
            {
                $newname = uniqid().'.'.$model->image->extensionName;
                $path = Yii::getPathOfAlias('webroot').'/images/avatar/'.$newname;
                $model->avatar = $newname;
            }
			if($model->save())
            {

                if(isset($model->image))
                {
                    $model->image->saveAs($path);
                    $avatar = new YiiResize();
                    $avatar->height = 100;
                    $avatar->quality =95;
                    $avatar->destination =  Yii::getPathOfAlias('webroot').'/images/avatar';
                    $avatar->fileName = $newname;
                    $avatar->src = Yii::getPathOfAlias('webroot').'/images/avatar/'.$newname;
                    $avatar->rewrite = true;
                    $avatar->resize();

                }
                Yii::app()->user->setFlash('success',Yii::t('UserModule.base','User created successfully.'));
                $this->redirect(array('view','id'=>$model->id));
            }
		}

		$this->render('create',array(
			'model'=>$model,
		));
	}

	/**
	 * Updates a particular model.
	 * If update is successful, the browser will be redirected to the 'view' page.
	 * @param integer $id the ID of the model to be updated
	 */
	public function actionUpdate($id)
	{
		$model=$this->loadModel($id);
		// Uncomment the following line if AJAX validation is needed
		 $this->performAjaxValidation($model);

		if(isset($_POST['User']))
		{
            $oldavatar = $model->avatar;
			$model->attributes=$_POST['User'];

                $model->image=CUploadedFile::getInstance($model,'avatar');
                if(isset($model->image))
                {
                    $newname = uniqid().'.'.$model->image->extensionName;
                    $path = Yii::getPathOfAlias('webroot').'/images/avatar/'.$newname;
                    $model->avatar = $newname;
                }
                else
                {
                    //Если нет нового аватара, то добавляется старый
                    $model->avatar = $oldavatar;
                }

			if($model->save())
            {

                if(isset($model->image))
                {
                    $model->image->saveAs($path);
                    $avatar = new YiiResize();
                    $avatar->height = 100;
                    $avatar->quality =95;
                    $avatar->destination =  Yii::getPathOfAlias('webroot').'/images/avatar';
                    $avatar->fileName = $newname;
                    $avatar->src = Yii::getPathOfAlias('webroot').'/images/avatar/'.$newname;
                    $avatar->rewrite = true;
                    $avatar->resize();

                }
                Yii::app()->user->setFlash('success',Yii::t('UserModule.base','Profile update success.'));
                $this->redirect(array('view','id'=>$model->id));
            }
		}
		$this->render('update',array(
			'model'=>$model,
		));
	}
	/**
	 * Deletes a particular model.
	 * If deletion is successful, the browser will be redirected to the 'admin' page.
	 * @param integer $id the ID of the model to be deleted
	 */
	public function actionDelete($id)
	{
		$this->loadModel($id)->delete();

		// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
		if(!isset($_GET['ajax']))
            Yii::app()->user->setFlash('success',Yii::t('UserModule.base','User successfully deleted.'));
			$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
	}

	/**
	 * Lists all models.
	 */
	public function actionIndex()
	{
		$dataProvider=new CActiveDataProvider('User',array(
            'pagination'=>array('pageSize'=>5)
        ));
		$this->render('index',array(
			'dataProvider'=>$dataProvider,

		));
	}

	/**
	 * Manages all models.
	 */
	public function actionAdmin()
	{
		$model=new User('search');
		$model->unsetAttributes();  // clear any default values
		if(isset($_GET['User']))
			$model->attributes=$_GET['User'];

		$this->render('admin',array(
			'model'=>$model,
		));
	}

    /**
     * Отправка на email пользователя уведомления
     */
    public function actionSendEmail()
    {

        if($_GET['id'] === Yii::app()->user->id)
        {
            Yii::app()->user->setFlash('message',Yii::t('UserModule.base','You can not send a notice to yourself.'));
            $this->redirect(Yii::app()->createUrl('/user/backend/admin'));
        }

        $model = new NoteForm;
        $model->id = $_GET['id'];
        $model->name = $_GET['name'];
        $model->email = $_GET['email'];
        $this->performAjaxValidation($model);

        if(isset($_POST['NoteForm']) && !Yii::app()->request->isAjaxRequest)
        {
           $model->attributes = $_POST['NoteForm'];
           if($model->validate())
           {
           $mail = new YiiMailer();
           $mail->protocol = 'smtp';
           $mail->port = 465;
           $mail->charset = 'utf-8';
           $mail->SMTPSecure = 'ssl';
           $mail->mail_domain = Yii::app()->getModule('user')->params->mailDomain;
           $mail->login = Yii::app()->getModule('user')->params->adminEmail;
           $mail->name = Yii::app()->params->Brand;
           $mail->password = Yii::app()->getModule('user')->params->adminEmailPass;
           $mail->from = Yii::app()->getModule('user')->params->adminEmail;
           $mail->subject = Yii::t('UserModule.base','Notification.');
           $mail->html = $model->message;
           $mail->recipient =$model->name;
           $mail->to = $model->email;
           $mail->send();
               if($mail){
                   Yii::app()->user->setFlash('message',Yii::t('UserModule.base','Notice sent by mail.'));
                   $this->redirect(Yii::app()->createUrl('/user/backend/success'));
               }
           }
        }
        $this->render('note',array('model'=>$model));
    }
    public function actionSuccess()
    {
        if(Yii::app()->user->hasFlash('message'))
        {
            $message = Yii::app()->user->getFlash('message');
            $this->render('success', array('success'=>$message));
        }else{
            throw new CHttpException(404,'Page not found');
        }
    }


	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 * @param integer $id the ID of the model to be loaded
	 * @return User the loaded model
	 * @throws CHttpException
	 */
	public function loadModel($id)
	{
		$model=User::model()->findByPk($id);
		if($model===null)
			throw new CHttpException(404,'The requested page does not exist.');
		return $model;
	}

	/**
	 * Performs the AJAX validation.
	 * @param User $model the model to be validated
	 */
	protected function performAjaxValidation($model)
	{
		if(isset($_POST['ajax']) && $_POST['ajax']==='user-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
	}

    //Данный ментод изменяет статус(Таблица User колонка active ) пользователя
    public function actionChangeStatusActive($id)
    {
           if(is_numeric($id) && Yii::app()->user->id !== $id)
           {
               $sql = "UPDATE {{user}} SET active= ABS(active - 1) WHERE id=:id ";
               $db = Yii::app()->db;
               $comm = $db->createCommand($sql);
               $comm->bindParam(':id',$id,PDO::PARAM_INT);
               $comm->query();
               echo $id;
           }
        else
        {
            $errorMessage = array('error'=>Yii::t('UserModule.base','You can not block your own account'));
            echo json_encode($errorMessage);
        }
    }

}
